//
//  NewsParser.m
//  Pink
//
//  Created by ZhongDaYunKe on 15/12/5.
//  Copyright © 2015年 ycy. All rights reserved.
//

#import "NewsParser.h"

@implementation NewsParser


- (instancetype)init {
    self = [super init];
    NSString *pattern = @"[a-zA-z]+://[^\\s]*";
    self.regex = [[NSRegularExpression alloc] initWithPattern:pattern options:kNilOptions error:nil];
    return self;
}
- (BOOL)parseText:(NSMutableAttributedString *)text selectedRange:(NSRangePointer)range {
    __block BOOL changed = NO;
    [_regex enumerateMatchesInString:text.string options:NSMatchingWithoutAnchoringBounds range:text.rangeOfAll usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
        if (!result) return;
        NSRange range = result.range;
        if (range.location == NSNotFound || range.length < 1) return;
        
        NSRange urlRange = NSMakeRange(range.location + 5, range.length - 6);
        NSAttributedString *url = [text attributedSubstringFromRange:urlRange];
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
        [imageView setImageWithURL:[NSURL URLWithString:url.string] placeholder:nil options:YYWebImageOptionProgressiveBlur completion:^(UIImage *image, NSURL *url, YYWebImageFromType from, YYWebImageStage stage, NSError *error) {
            
        }];
        NSMutableAttributedString *imageString = [NSMutableAttributedString attachmentStringWithContent:imageView contentMode:UIViewContentModeCenter attachmentSize:imageView.size alignToFont:[UIFont systemFontOfSize:16] alignment:YYTextVerticalAlignmentCenter];
        [text.mutableString deleteCharactersInRange:range];
        
        [imageString insertString:@"\n" atIndex:0];
        [imageString appendString:@"\n"];
        [text insertAttributedString:imageString atIndex:range.location];
        
        
//        [text deleteCharactersInRange:range];
//        [text replaceCharactersInRange:range withAttributedString:imageString];

        
    changed = YES;
    }];
    return changed;
}



@end
